<?php

class Karaoke_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
	private $_auth;
	private $_acl;
	
	private $_noAuth = array(
		'module' => 'default',
		'controller' => 'login',
		'action' => 'index'
	);
	
	private $_noAcl = array(
		'module' => 'default',
		'controller' => 'error',
		'action' => 'privileges'
	);
	
	public function __construct($auth, $acl)
	{
		$this->_auth = $auth;
		$this->_acl = $acl;
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		if ($this->_auth->hasIdentity()){
		
			/**
			 * We must load User model here and set 'user' variable in Zend_Registry.
			 * $role should be set if identity exists.
			 */
		} else {
			$role = 'guest';
		}
		
		$controller = $request->getControllerName();
		$action = $request->getActionName();
		$module = $request->getModuleName();
		
		$resource = $controller;
		
		if (!$this->_acl->has($resource))
		{
			$resource = null;
		}
		
		if (!$this->_acl->isAllowed($role, $resource, $action))
		{
			if (!$this->_auth->hasIdentity())
			{
				$module = $this->_noAuth['module'];
				$controller = $this->_noAuth['controller'];
				$action = $this->_noAuth['action'];
			} else {
				$module = $this->_noAcl['module'];
				$controller = $this->_noAcl['controller'];
				$action = $this->_noAcl['action'];
			}
		}
		
		$request->setModuleName($module);
		$request->setControllerName($controller);
		$request->setActionName($action);
	}
}